package com.choudou5.solr.framework.util;

import com.choudou5.solr.framework.bean.HttpRespBean;
import com.choudou5.solr.framework.constants.ErrorResp;
import com.choudou5.solr.framework.constants.SysConsts;
import com.choudou5.solr.util.StrUtil;
import com.choudou5.solr.util.exception.BizException;
import com.choudou5.solr.util.JsonUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLEncoder;

/**
 * @Name：页面跳转工具类
 * @@author choudou5
 * @@date 2018-07-14
 */
public class PageJumpUtil {

    private final static  Logger logger = LoggerFactory.getLogger(PageJumpUtil.class);

    public static void forward(String page, HttpServletRequest request, HttpServletResponse response) {
        response.setCharacterEncoding("UTF-8");
        try {
            if(page != null) {
                //跳转后地址栏不会发生变化。传值可以使用三种方法：url中带parameter，session，request.setAttribute
                request.getRequestDispatcher(SysConsts.PAGE_ROOT+page+".jsp").forward(request, response);
            } else {
                response.sendError(404);
            }
        } catch (Exception e) {
            logger.error("forward fail", e);
        }
    }

    public static void errorOut(ErrorResp errorResp, HttpServletRequest request, HttpServletResponse response){
        errorOut(errorResp, null, request, response);
    }

    public static void errorOut(Throwable e, ErrorResp errorResp, HttpServletRequest request, HttpServletResponse response){
        String message = null;
        if(e instanceof BizException)
            message = e.getMessage();
        errorOut(errorResp, message, request, response);
    }

    public static void errorOut(ErrorResp errorResp, String message, HttpServletRequest request, HttpServletResponse response){
        boolean isAjax = RequestUtil.isAjax(request);
        if(isAjax){
            writeJson(errorResp, message, response);
        }else{
            if(errorResp.getPage() != null)
                redirect(errorResp.getPage(), null, response);
            else
                writeJson(errorResp, message, response);
        }
    }

    public static void redirect(String page, HttpServletResponse response){
        redirect(page, null, response);
    }

    public static void toLogin(HttpServletRequest request, HttpServletResponse response){
        boolean isAjax = RequestUtil.isAjax(request);
        if(isAjax){
            writeJson(ErrorResp.UN_LOGIN, response);
        }else{
            forward(SysConsts.PAGE_LOGIN, request, response);
        }
    }

    public static void redirect(String page, String tipMsg, HttpServletResponse response){
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html");
        try {
            //追加提示消息
            if(tipMsg != null){
                if(page.indexOf("?") != -1){
                    page = page + "&tipMsg="+ URLEncoder.encode(tipMsg, "utf-8");
                }else{
                    page = page + "?tipMsg="+ URLEncoder.encode(tipMsg, "utf-8");
                }
            }

            if(page != null) {
                response.sendRedirect(page);
            } else {
                response.sendError(404);
            }
        } catch (IOException e) {
            logger.error("redirect fail", e);
        }
    }

    public static void writeJson(ErrorResp errorResp, HttpServletResponse response) {
        writeJson(errorResp, null, response);
    }

    public static void writeJson(ErrorResp errorResp, String message, HttpServletResponse response) {
        if(StrUtil.isBlank(message))
            message = errorResp.getDesc();
        HttpRespBean respBean = new HttpRespBean(message, errorResp.getCode());
        writeJson(respBean, response);
    }

    public static void writeJsonInvalidParam(String message, HttpServletResponse response) {
        writeJson(ErrorResp.INVALID_PARAM, message, response);
    }

    public static void writeJsonOk(String message, HttpServletResponse response) {
        HttpRespBean respBean = new HttpRespBean(message, 200);
        writeJson(respBean, response);
    }

    public static void writeJsonObjOk(Object obj, HttpServletResponse response) {
        writeJson(new HttpRespBean(obj, "ok", 200), response);
    }

    public static void writeJson(HttpRespBean respBean, HttpServletResponse response) {
        writeObjToJson(respBean, response);
    }

    public static void writeObjToJson(Object object, HttpServletResponse response) {
        PrintWriter out = null;
//        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/json; charset=utf-8");
        try {
            out = response.getWriter();
//            Writer out = new OutputStreamWriter(response.getOutputStream(), StandardCharsets.UTF_8);
            out.write(JsonUtil.toStr(object));
            out.close();
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
